package com.sunshine.user.service.impl;

import com.sunshine.user.entity.UserProfiles;
import com.sunshine.user.mapper.UserProfilesDao;
import com.sunshine.user.service.UserProService;
import com.sunshine.util.TokenUtil;
import com.sunshine.util.minio.MinIOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sunshine.commcon.util.entity.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Service
public class UserProServiceImpl implements UserProService {
    
    @Resource
    private UserProfilesDao userProfilesDao;
    
    @Resource
    private MinIOUtil minIOUtil;
    
    public Result<UserProfiles> findUserProfileByToken(HttpServletRequest request) {
        log.info("开始从请求中获取用户ID");
        // 从token中获取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        log.info("获取到的用户ID: {}", userId);
        
        if (userId != null) {
            // 根据用户ID查询用户资料
            log.info("开始查询用户资料，userId: {}", userId);
            UserProfiles profiles = userProfilesDao.findByUserId(userId);
            log.info("查询到的用户资料: {}", profiles);
            return profiles != null ? Result.ok(profiles) : Result.fail();
        }
        log.warn("未能从token中获取到有效的用户ID");
        return null;
    }

    @Override
    public Result<Boolean> addUserProfile(UserProfiles userProfiles) {
        int insert = userProfilesDao.insert(userProfiles);
        return insert > 0 ? Result.ok(true) : Result.fail();
    }
    
    @Override
    public Result<Boolean> addUserProfile(UserProfiles userProfiles, MultipartFile avatarFile) {
        try {
            // 如果有头像文件，上传到MinIO并获取URL
            if (avatarFile != null && !avatarFile.isEmpty()) {
                String avatarUrl = minIOUtil.uploadFile(avatarFile, "avatars/");
                userProfiles.setAvatarUrl(avatarUrl);
            }
            
            int insert = userProfilesDao.insert(userProfiles);
            return insert > 0 ? Result.ok(true) : Result.fail();
        } catch (Exception e) {
            log.error("添加用户资料失败", e);
            return Result.fail("添加用户资料失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> updateUserProfile(UserProfiles userProfiles, HttpServletRequest request) {
        // 获取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        userProfiles.setUserId(userId);
        
        // 获取更新前的用户信息
        UserProfiles oldProfile = userProfilesDao.findByUserId(userId);
        
        // 如果头像URL有变化，删除旧的头像文件
        if (oldProfile != null && oldProfile.getAvatarUrl() != null && 
            !Objects.equals(oldProfile.getAvatarUrl(), userProfiles.getAvatarUrl())) {
            try {
                // 从完整的URL中提取对象名称
                String oldAvatarUrl = oldProfile.getAvatarUrl();
                String objectName = extractObjectNameFromUrl(oldAvatarUrl);
                if (objectName != null) {
                    minIOUtil.deleteFile(objectName);
                    log.info("已删除旧头像文件: {}", objectName);
                }
            } catch (Exception e) {
                log.error("删除旧头像文件失败: {}", oldProfile.getAvatarUrl(), e);
            }
        }
        
        log.info("开始更新用户资料，userProfiles: {}", userProfiles);
        int update = userProfilesDao.update(userProfiles);
        return update > 0 ? Result.ok(true) : Result.fail();
    }
    
    /**
     * 从MinIO的预签名URL中提取对象名称
     *
     * @param url 预签名URL
     * @return 对象名称
     */
    private String extractObjectNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        try {
            // 查找bucket名称后的位置
            String bucketName = "sunshine-shopping";
            int bucketIndex = url.indexOf("/" + bucketName + "/");
            if (bucketIndex != -1) {
                String objectPart = url.substring(bucketIndex + bucketName.length() + 2);
                int paramIndex = objectPart.indexOf("?");
                if (paramIndex != -1) {
                    objectPart = objectPart.substring(0, paramIndex);
                }
                return objectPart;
            }
        } catch (Exception e) {
            log.warn("从URL提取对象名称失败: {}", url, e);
        }
        return null;
    }
}